<template>
  <el-splitter>
    <ElSplitterPanel>
      <ContentView v-for="(layout, i) in data" :layout="layout" :key="i" />
    </ElSplitterPanel>
    <ElSplitterPanel size="20%" collapsible>
      <el-splitter layout="vertical">
        <ElSplitterPanel :size="210">
          <TreeView ref="treeViewRef" :data="data" class="full" />
        </ElSplitterPanel>
        <ElSplitterPanel>
          <Property />
        </ElSplitterPanel>
        <ElSplitterPanel>
          <CssEditor v-if="currentArea" v-model="currentArea.style" />
        </ElSplitterPanel>
      </el-splitter>
    </ElSplitterPanel>
  </el-splitter>
</template>
<script setup lang="ts">
  import { computed, provide, ref, watch } from 'vue';
  import { ElSplitter, ElSplitterPanel } from 'element-plus';
  import Property from './Property.vue';
  import TreeView from './TreeView.vue';
  import ContentView from './ContentView.vue';
  import { CssEditor } from '../../CssEditor';
  import { genNodeId } from '@/utils/system';
  import { cloneDeep } from 'lodash-es'
  import { LayoutConfiguration } from '@/views/dev-types';
  import { TreeViewType } from '..';

  const props = defineProps<{modelValue?: LayoutConfiguration}>()
  const emits = defineEmits(['update:modelValue'])

  const treeViewRef = ref<TreeViewType>()
  provide('treeViewRef', treeViewRef)
  const currentArea = computed(() => treeViewRef.value?.getCurrentArea())

  function init() {
    if(props.modelValue) {
      const layout = cloneDeep(props.modelValue)
      addId(layout)
      return [layout]
    }

    return []
  }

  function addId(layout: any) {
    layout.id = genNodeId()
    if(layout.children) {
      for(const child of layout.children) addId(child)
    }
  }

  function formatData() {
    if(data.value.length > 0) {
      const layout = cloneDeep(data.value[0])
      removeExtra(layout)
      return layout
    }

    return void 0
  }

  function removeExtra(layout) {
    delete layout.id
    delete layout.classList
    if(layout.children) {
      for(const child of layout.children) removeExtra(child)
    }
  }
  const data = ref(init())
  let outter = false
  let inner = false

  watch(() => props.modelValue, () => {
    if(inner) {
      inner = false
      return
    }
    
    outter = true
    data.value = init()
  }, { deep: true })
  watch(() => data.value, () => {
    if(outter) {
      outter = false
      return
    }

    inner = true
    emits('update:modelValue', formatData())
  }, { deep: true })
</script>

<style lang="less" scoped>
  
</style>